# 作者： 李泉志
# 2025年01月06日18时15分秒
# 2947029073@qq.com
"""
集合是无序的，用哈希实现，使用是为了去重
"""


def set_demo():
    set1 = {}  # 空字典，而不是集合
    print(type(set1))
    set1 = set()  # 空集合初始化
    print(type(set1))
    set1 = {1, 2, 3, 4, 5}
    print(type(set1))
    print(set1)
    # 不能set[2]


def set_operation():
    set1 = {1, 2, 3, 4}
    set2 = {4, 5, 6, 7, 8}
    # 添加元素
    set1.add(5)
    set1.update([6, 7])
    print('set1:', set1)

    print('-' * 50)
    # 复制集合
    set3 = set1.copy()  # copy地址不同，直接=赋值地址相同
    print('set3:', set3)
    print('-'*50)

    # 并集
    print('并集')
    set1 = {1, 2, 3}
    set2 = { 5, 6, 7, 8}
    set1.update(set2)  # 等价set1 = set1 | set2 ,  setx = set1.union(set2)
    print('set1:', set1)
    print('-' * 50)

    # 差集
    print('差集')
    set4 = set1.difference(set2)  # 等价set4 = set1 - set2
    print('set4:', set4)
    set1.difference_update(set2)  # 无返回值，直接在set1中删
    print('set1:', set1)
    print('-' * 50)

    # 交集
    print('交集')
    set2 = {2,3}
    set5 = set1.intersection(set2)  # 等价set5 = set1 & set2
    print('set5:', set5)
    set1.intersection_update(set2)  # 无返回值，直接在set1中删
    print('set1:', set1)
    print('-' * 50)


    # 判断是否 无相同元素，没有返回True，有返回False
    set2 = {4, 5}
    print(set1.isdisjoint(set2))  # True不相交
    print('-' * 50)

    # 是否为子集
    set2 = {1, 2, 3}
    print(set1.issubset(set2))  # True，set1是set2的子集
    print('-' * 50)

    # 删除元素
    set2.remove(2)  # 若不存在，报错
    set2.discard(3)  # 若不存在，不报错
    print('set2:', set2)

    # 判断元素是否存在
    print(2 in set2)  # False


def use_generator():
    """
    集合生成式
    :return:
    """

    my_set = set(x for x in range(10))
    print(my_set)

    # 也支持推导式
    my_set = {x for x in 'abracadabra' if x not in 'abc'}
    print(my_set)  # {'r', 'd20'}


if __name__ == '__main__':
    # set_demo()
    pass
    #set_operation()
    use_generator()
